package com.jhws.sys.cms.controller;

import com.jhws.business.aliyun.service.OSSClientService;
import com.jhws.util.GetId;
import com.jhws.sys.cms.bo.ImagesOss;
import com.jhws.sys.cms.service.ImagesOssService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于oss无状态图片上传，就是没有关联资源的图片
 */
@Controller
@RequestMapping("/cms/imagesOss")
public class ImagesOssController {

    @Resource
    private ImagesOssService imagesOssService;
    @Resource
    private OSSClientService ossClientService;

    /**
     * @upfile 富文本中的upfile，要对应一致
     */
    @RequestMapping("/uploadimage.x")
    @ResponseBody
    public Map<String, Object> upload(@RequestParam("upfile") MultipartFile upfile,
                                      HttpServletRequest request,
                                      HttpServletResponse response,
                                      String editorId) throws Exception {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //上传文件到远程图片服务器
        String suffix = FilenameUtils.getExtension(upfile.getOriginalFilename());
        String type = "." + suffix;
        String filename = GetId.randomID() + type;
        String path = "cms/file/" + filename;
        ossClientService.updateFile(path, upfile.getInputStream());
        String url = ossClientService.getUrl(path, false);
        ImagesOss imagesOss = new ImagesOss();
        imagesOss.setOssUrl(path);
        imagesOss.setResourceUId(editorId);
        imagesOssService.saveImagesOssInfo(imagesOss);

        Map<String, Object> ret = new HashMap<>();
        //ret.put("path", appPath + "/" + currentMonth + "/");
        ret.put("filename", filename);
        ret.put("original", upfile.getOriginalFilename());
        ret.put("name", filename);
        ret.put("url", url);
        ret.put("state", "SUCCESS");
        ret.put("type", type);
        ret.put("size", upfile.getSize());
        return ret;
    }
}
